import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

const Login = () => import('../views/Login.vue')
const Users = () => import('../views/Users/Users.vue')
const Detail = () => import('../views/Users/children/Detail.vue')
const Backstage = () => import('../views/Users/children/Backstage.vue')
const Profile = () => import('../views/Users/children/profile.vue')
const Error = () => import('../views/Error.vue')

Vue.use(VueRouter)

const routes = [
  //首页
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: "首页"
    },
    // 路由独享的守卫
    beforeEnter: (to, from, next) => {
      console.log(to);
      if (to.path == '/login') {
        next()
      } else {
          alert('你没有登陆哦');
          // next('/login')
          next()
      
      }
    }
  },
  //登录
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: "登录"
    }
  },
  //用户页
  {
    path: '/users/:id',
    name: 'Users',
    component: Users,
    meta: {
      //只有登录才可以进入此界面
      requireAuth: true,
      title: "用户界面"
    },
    //注册子路由，用于路由嵌套
    children: [
      {
        path: "",
        redirect: "detail"
      },
      {
        path: "detail",
        component: Detail,
        meta: {
          title: "用户详情"
        }
      },
      {
        path: "backstage",
        component: Backstage,
        meta: {
          title: "用户后台管理"
        }
      },
      {
        path: "profile",
        component: Profile,
        meta: {
          title: "用户档案"
        }
      },
    ]
  },
  {
    path: "*",
    component: Error,
    meta: {
      title: "Error"
    }

  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  linkActiveClass: "active",
  routes
})

//每次通过vue-router进行页面跳转，
// 都会触发beforeEach这个钩子函数这个回调函数共有三个参数，to，from，next这三个参数，
// to表示我要跳转的目标路由对应的参数，
// from表示来自那个路由，就是操作路由跳转之前的，即将离开的路由对应的参数，
// next是一个回调函数，一定要调用next方法来resolve这个钩子函数；

//前置守卫
router.beforeEach((to, from, next) => {
  //从from跳转到to
  document.title = to.matched[0].meta.title;
  next();
})
//后置钩子
router.afterEach((to, from) => {
  console.log(to);
  console.log(from);
  console.log("路由加载完成");
})

export default router
